package com.ocom.wxapi.controller;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetLoginCompanyListRequest;
import com.ocom.common.request.web.ReplaceTokenRequest;
import com.ocom.common.request.wx.AccountListRequest;
import com.ocom.common.request.wx.GetCompanyListInfoRequest;
import com.ocom.common.request.wx.RecentLoginListRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.wxapi.client.CompanyClientService;
import com.ocom.wxapi.client.HumanClientService;
import com.ocom.wxapi.client.OauthClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CompanyController {

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private OauthClientService oauthClientService;

    @Autowired
    private HumanClientService humanClientService;

    @Value("${platformSecret}")
    private String platformSecret;

    @PostMapping("/IndexPage/recentLoginList")
    public Result recentLoginList(@Validated  RecentLoginListRequest request){
        GetLoginCompanyListRequest getLoginCompanyListRequest = new GetLoginCompanyListRequest();
        getLoginCompanyListRequest.setAdminId(request.getAdminId());
        getLoginCompanyListRequest.setQueryMode(0);
        return this.companyClientService.getLoginCompanyList(getLoginCompanyListRequest);
    }

    @PostMapping("/IndexPage/accountList")
    public Result accountList(@Validated AccountListRequest request){
        GetLoginCompanyListRequest getLoginCompanyListRequest = new GetLoginCompanyListRequest();
        getLoginCompanyListRequest.setComId(request.getComId());
        getLoginCompanyListRequest.setQueryMode(1);
        return this.companyClientService.getLoginCompanyList(getLoginCompanyListRequest);

    }

    @PostMapping("/IndexPage/companyList")
    public Result companyList(GetCompanyListInfoRequest getCompanyListInfoRequest){
        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        companyListInfoVo.setComId(getCompanyListInfoRequest.getComId());
        companyListInfoVo.setComName(getCompanyListInfoRequest.getComName());
        companyListInfoVo.setOnly(2);
        companyListInfoVo.setPage(-1);
        companyListInfoVo.setSize(-1);
        return this.companyClientService.GetCompanyListInfo(companyListInfoVo);
    }

    @PostMapping("/IndexPage/getToken")
    public Result getToken(ReplaceTokenRequest request){
        Long role = SecurityUtils.getYoCiUser().getRole();
        if (role != 0l && role != 1L) {
            if(!SecurityUtils.getYoCiUser().getPermissions().contains("sys:user:master")){
                return ResultUtil.error(ResultEnum.Err_4);
            }
        }

        Result result3 = humanClientService.getMngUserInfoById(request.getId());

        if(result3.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_303);
        }

        EntityMngUserInfo entityMngUserInfo = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityMngUserInfo.class);

        //下载hutool依赖
        String key = "tbk0Xa67cEePvv14g5Pf1MPzIceQMN14"; // 密钥（8 字节）
        String username = entityMngUserInfo.getUserName();
        String password = platformSecret;
        username = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).encryptBase64(username);
        password = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).encryptBase64(password);
        username = new String(HexUtil.encodeHex(username.getBytes(StandardCharsets.UTF_8)));
        password =  new String(HexUtil.encodeHex(password.getBytes(StandardCharsets.UTF_8)));
        
        Result result = oauthClientService.loginWeb(
                username,
                password ,
                entityMngUserInfo.getRole().toString(),
                "code_auth",
                "client_1",
                "123456"
        );

        if(result.getCode()!=200){
            return result;
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));


        Map<String , Object> resMap =new HashMap<>();

        resMap.put("token",jsonObject.get("access_token"));

        resMap.put("menuTree",new ArrayList<>());


        Result result1  = companyClientService.GetCompanyListInfoOne(entityMngUserInfo.getComId());

        if(result1.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_301);
        }
        EntityCompanyList entityCompanyList =JSON.parseObject(JSON.toJSONString(result1.getData()),EntityCompanyList.class);
        resMap.put("comName",entityCompanyList.getComName());


        JSONObject jsonObject1 =new JSONObject();
        jsonObject1.put("saasNo",entityCompanyList.getSaasId());
        jsonObject1.put("xfVer",entityCompanyList.getXfStatus());
        jsonObject1.put("mjVer",entityCompanyList.getMjStatus());
        jsonObject1.put("role",entityMngUserInfo.getRole());
        jsonObject1.put("webOrApp","1");
        Result result2 = humanClientService.getSaasMenuByRole(jsonObject1);

        if(result2.getCode()==200){
            JSONObject jsonObject3 = JSON.parseObject(JSON.toJSONString(result2.getData()));
            resMap.put("menuTree",jsonObject3.get("menuTree"));
        }

        return ResultUtil.success(resMap);
    }
}
